<?php

namespace app\zyhsapi\model\comment;

use app\zyhsapi\model\BaseCacheZyhs;
use XznsTools\cache\zyhs\CacheManageZyhs;

class ZyhsArticleCommentGood extends BaseCacheZyhs
{
    protected $table = 'good_wechat.zyhs_article_comment_good';

    protected $cacheModel = 'zyhs.content_comment_good';

    /**
     * 获取 用户 点赞的评论或回复IDs
     * @param int $uid
     * @param int $cType 1=>评论  2=>评论回复
     * @return array
     * @throws \Exception
     */
    public function getUserCommentGoodCids(int $uid, int $cType): array
    {
        $resData = CacheManageZyhs::getInstance()
            ->setCacheConfig($this->cacheModel, $uid)
            ->setListKeyType($cType)// 类型 用于分页 例如 0全部 1待支付 已支付 //
            ->setPage(-1)
            ->setSort('desc')
            ->setListCacheTime(86400)    // 一天 过期时间
            ->getListPageDataIds(function ($isCache = true, $sortType = 'desc') use ($uid, $cType)
            {
                try
                {
                    $data = $this->where(['uid' => $uid, 'ctype' => $cType])->column('create_time', 'cr_id');
                    $resData = [];
                    foreach ($data as $id => $createTime)
                    {
                        $resData[$id] = ['create_time' => $createTime];
                    }

                    return $resData;
                }
                catch (\Exception $e)
                {
                    return [];
                }
            }, 'create_time', 0);
        return $resData['data'] ? array_keys($resData['data']) : [];
    }

    /**
     * 添加点赞
     * @param array $data
     * @return bool
     */
    public function addZan(array $data)
    {
        try
        {
            $this->save($data);

            $this->listDataAdd($data['uid'], [$data['cr_id'] => $data['create_time']], $data['ctype']);
            return true;
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return false;
        }
    }

    /**
     * 取消 点赞
     * @param array $data
     * @return bool
     */
    public function delZan(array $data)
    {
        try
        {
            $this->where(['uid' => $data['uid'], 'ctype' => $data['ctype'], 'cr_id' => $data['cr_id']])->delete();

            $this->listDataDel($data['uid'], [$data['cr_id']], $data['ctype']);
            return true;
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return false;
        }
    }
}